<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button onclick="test1()">请求一</button><br/>
    <button onclick="test2()">get请求</button>
    <button onclick="test3()">get请求</button>
    <button onclick="post1()">post请求</button>
    <button onclick="post2()">post请求</button>
    <button onclick="json()">json请求</button>
    <div></div>
    <script>
        const div = document.querySelector('div');
        const url = 'http://127.0.0.1:8080/';
        // 基本请求
        function test1() {
            fetch(url + 'test1')
                .then(data => data.text())
                .then(data => div.innerHTML = data);
        }

        // get添加参数
        function test2() {
            fetch(url + 'books?id=123')
                .then(data => data.text())
                .then(data => div.innerHTML = data);
        }

        function test3() {
            fetch(url + 'books/456')
                .then(data => data.text())
                .then(data => div.innerHTML = data);
        }

        // post添加参数
        function post1() {
            fetch(url + 'books2', {
                    method: 'post',
                    body: 'uname=lisi&pwd=123',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(data => data.text())
                .then(data => div.innerHTML = data)
                .catch(info => div.innerHTML = info)
                .finally(() => console.log("post1 finish"));
        }

        function post2() {
            fetch(url + 'books3', {
                    method: 'post',
                    body: JSON.stringify({
                        uname: 'lisi',
                        pwd: 456789
                    }),
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                .then(data => data.text())
                .then(data => div.innerHTML = data)
                .catch(info => div.innerHTML = info)
                .finally(() => console.log("post2 finish"));
        }

        function json() {
            fetch(url + 'json', {
                    method: 'post',
                    body: JSON.stringify({
                        uname: 'json',
                        pwd: 270628297
                    }),
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                .then(data => data.json())
                .then(data => div.innerHTML = `${data.uname} -- ${data.pwd}`)
                .catch(info => div.innerHTML = info)
                .finally(() => console.log("json finish"));
        }
    </script>
</body>

</html>